package cn.ztydata.teachingsystem.heaven.web.controller;

import cn.ztydata.teachingsystem.exception.UploadException;
import cn.ztydata.teachingsystem.heaven.cons.Constants;
import cn.ztydata.teachingsystem.heaven.entity.*;
import cn.ztydata.teachingsystem.heaven.exception.ExcelException;
import cn.ztydata.teachingsystem.heaven.service.*;
import cn.ztydata.teachingsystem.heaven.util.UploadUtil;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResult;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * 数据导入控制器类
 * Created by chenxin on 2014/11/27.
 */
@Controller
@RequestMapping("/import")
public class ImportController extends BaseController {
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private SpecialtyService specialtyService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private CourseGroupService courseGroupService;
    @Autowired
    private CourseArrangeService courseArrangeService;
    @Autowired
    private ClassService classService;

    private List<String> fileTypes = Lists.newArrayList("xls", "xlsx"); //上传类型白名单

    /**
     * 导入教师信息
     * @param teacherFile excel文件
     * @return json
     * @throws IOException IO异常
     *
     * @author cx
     * @since 2014-11-29
     */
    @RequestMapping(value = "/teacher", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult importTeachers(@RequestParam MultipartFile teacherFile) throws IOException {
        List<Teacher> teacherList = null;

        try {
            //校验上传的文件
            UploadUtil.validateFile(teacherFile, fileTypes);
            //获取导入的教师信息集合
            teacherList = teacherService.readFromExcel(teacherFile.getInputStream());

            //检查导入教师信息中的工号重复冲突问题
            teacherService.checkForNum(teacherList);

            //批量新增教师信息
            teacherService.saveTeachers(teacherList);
        } catch (UploadException | ExcelException ex) {
            log.debug("import excel file failed");

            return new JsonResult(false, ex.getMessage().isEmpty() ? "Excel导入失败" : ex.getMessage());
        } finally {
            if (teacherList != null) {
                log.debug("teacherList != null");

                teacherList.clear();
                teacherList = null;
            }
        }

        log.debug("教师excel文件导入成功");
        return new JsonResult(true, "");
    }

    /**
     * 导入系部信息
     * @param departFile excel文件
     * @return json
     * @throws IOException io异常
     *
     * @author cx
     * @since 2014-11-29
     */
    @RequestMapping(value = "/depart", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult importDepts(@RequestParam MultipartFile departFile) throws IOException {
        List<Department> deptList = null;

        try {
            //校验上传的文件
            UploadUtil.validateFile(departFile, fileTypes);
            //获取导入的系部信息集合
            deptList = departmentService.readFromExcel(departFile.getInputStream());

            //检查导入系部信息中的编码重复冲突问题
            departmentService.checkForNum(deptList);

            //批量新增系部信息
            departmentService.saveDepts(deptList);
        } catch (UploadException | ExcelException ex) {
            log.debug("Excel导入系部失败");
            return new JsonResult(false, ex.getMessage().isEmpty() ? "Excel导入失败" : ex.getMessage());
        } finally {
            if (deptList != null) {
                log.debug("deptList != null");

                deptList.clear();
                deptList = null;
            }
        }

        log.debug("导入系部信息成功");
        return new JsonResult(true, "");
    }

    /**
     * 导入专业信息
     * @param majorFile excel文件
     * @return json
     * @throws IOException io异常
     *
     * @author cx
     * @since 2014-11-29
     */
    @RequestMapping(value = "/major", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult importMajors(@RequestParam MultipartFile majorFile) throws IOException {
        List<Specialty> specialtyList = null;

        try {
            //校验上传的文件
            UploadUtil.validateFile(majorFile, fileTypes);
            //获取导入的系部信息集合
            specialtyList = specialtyService.readFromExcel(majorFile.getInputStream());

            //检查导入专业信息中的编码重复冲突问题
            specialtyService.checkForNum(specialtyList);

            //批量新增专业信息
            specialtyService.addSpecs(specialtyList);
        } catch (UploadException | ExcelException ex) {
            log.debug("Excel导入专业信息失败");
            return new JsonResult(false, ex.getMessage().isEmpty() ? "Excel导入失败" : ex.getMessage());
        } finally {
            if (specialtyList != null) {
                log.debug("specialtyList != null");

                specialtyList.clear();
                specialtyList = null;
            }
        }

        log.debug("Excel导入专业信息成功");
        return new JsonResult(true, "");
    }

    /**
     * 导入学生信息
     * @param studentFile excel文件
     * @return JsonResult
     * @throws IOException
     *
     * @author wyh
     * @since 2015-03-21
     */
    @RequestMapping(value = "/student", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult importStudents(@RequestParam MultipartFile studentFile) throws IOException {
        List<Student> studentList = null;

        try {
            //校验上传的文件
            UploadUtil.validateFile(studentFile, fileTypes);
            //获取导入的学生信息集合
            studentList = studentService.readFromExcel(studentFile.getInputStream());

            //检查导入学生信息中的编码重复冲突问题
            studentService.checkForNum(studentList);

            //批量新增学生信息
            studentService.saveStudents(studentList);
        } catch (UploadException | ExcelException ex) {
            log.debug("Excel导入学生信息失败");
            return new JsonResult(false, ex.getMessage().isEmpty() ? "Excel导入失败" : ex.getMessage());
        } finally {
            if (studentList != null) {
                log.debug("studentList != null");

                studentList.clear();
                studentList = null;
            }
        }

        log.debug("Excel导入学生信息成功");
        return new JsonResult(true, "成功");
    }

    /**
     * 导入学生异动
     * @param studentFile excel文件
     * @return JsonResult
     * @throws IOException
     *
     * @author wyh
     * @since 2015-03-21
     */
    @RequestMapping(value = "/studentDifferent", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult importStudentsChange(@RequestParam MultipartFile studentFile) throws IOException {
        List<Student> studentList = null;

        try {
            //校验上传的文件
            UploadUtil.validateFile(studentFile, fileTypes);

            //获取导入的学生异动集合
            studentList = studentService.readChangeFromExcel(studentFile.getInputStream());

            //判断条数
            if (studentList.size() > Constants.TOTAL_2K) {
                log.debug("导入数据量超过" + Constants.TOTAL_2K);
                throw new ExcelException("导入数据量超过" + Constants.TOTAL_2K);
            }

            //批量更新学生信息
            studentService.updateStudents(studentList);
        } catch (UploadException | ExcelException ex) {
            log.debug("Excel导入学生异动信息失败");
            return new JsonResult(false, ex.getMessage().isEmpty() ? "Excel导入失败" : ex.getMessage());
        } finally {
            if (studentList != null) {
                log.debug("studentList != null");

                studentList.clear();
                studentList = null;
            }
        }

        log.debug("Excel导入学生异动信息成功");
        return new JsonResult(true, "成功");
    }

    /**
     * 导入学生选课
     * @param studentFile excel文件
     * @return JsonResult
     * @throws IOException
     *
     * @author wyh
     * @since 2015-03-21
     */
    @RequestMapping(value = "/studentChooseLesson", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult importStudentsCourse(@RequestParam MultipartFile studentFile) throws IOException {

        List<StudentCourse> studentList = null;

        try {
            //校验上传的文件
            UploadUtil.validateFile(studentFile, fileTypes);

            //获取导入的学生选课集合
            studentList = studentService.readSCFromExcel(studentFile.getInputStream());

            //判断条数
            if (studentList.size() > Constants.TOTAL_5K) {
                log.debug("导入数据量超过" + Constants.TOTAL_5K);
                throw new ExcelException("导入数据量超过" + Constants.TOTAL_5K);
            }

            //批量更新学生选课信息
            studentService.saveSC(studentList);

        } catch (UploadException | ExcelException ex) {
            log.debug("Excel导入学生选课信息失败");
            return new JsonResult(false, ex.getMessage().isEmpty() ? "Excel导入失败" : ex.getMessage());
        } finally {
            if (studentList != null) {
                log.debug("studentList != null");

                studentList.clear();
                studentList = null;
            }
        }

        log.debug("Excel导入学生选课信息成功");
        return new JsonResult(true, "成功");
    }

    /**
     * 导入删除学生选课
     * @param studentFile excel文件
     * @return JsonResult
     * @throws IOException
     *
     * @author wyh
     * @since 2015-03-21
     */
    @RequestMapping(value = "/studentDeleteChooseLesson", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult importDeleteStudentsCourse(@RequestParam MultipartFile studentFile) throws IOException {

        List<StudentCourse> studentList = null;

        try {
            //校验上传的文件
            UploadUtil.validateFile(studentFile, fileTypes);

            //获取导入的学生选课集合
            studentList = studentService.readSCFromExcel(studentFile.getInputStream());

            //判断条数
            if (studentList.size() > Constants.TOTAL_5K) {
                log.debug("导入数据量超过" + Constants.TOTAL_5K);
                throw new ExcelException("导入数据量超过" + Constants.TOTAL_5K);
            }

            //批量更新学生选课信息
            studentService.deleteSC(studentList);

        } catch (UploadException | ExcelException ex) {
            log.debug("Excel导入删除学生选课信息失败");
            return new JsonResult(false, ex.getMessage().isEmpty() ? "Excel导入失败" : ex.getMessage());
        } finally {
            if (studentList != null) {
                log.debug("studentList != null");

                studentList.clear();
                studentList = null;
            }
        }

        log.debug("Excel导入删除学生选课信息成功");
        return new JsonResult(true, "成功");
    }

    /**
     * 导入课程群组
     * @param studentFile excel文件
     * @return JsonResult
     * @throws IOException
     *
     * @author wyh
     * @since 2015-03-24
     */
    @RequestMapping(value = "/lessonGroup", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult importCourseGroup(@RequestParam MultipartFile studentFile) throws IOException {
        List<CourseGroup> groupList = null;

        try {
            //校验上传的文件
            UploadUtil.validateFile(studentFile, fileTypes);

            //获取导入的课程群组集合
            groupList = courseGroupService.readFromExcel(studentFile.getInputStream());

            //判断是否有存在数据
            courseGroupService.checkForCode(groupList);

            //批量更新课程群组信息
            courseGroupService.saveCourseGroups(groupList);

        } catch (UploadException | ExcelException ex) {
            log.debug("Excel导入课程群组信息失败");
            return new JsonResult(false, ex.getMessage().isEmpty() ? "Excel导入失败" : ex.getMessage());
        } finally {
            if (groupList != null) {
                log.debug("studentList != null");

                groupList.clear();
                groupList = null;
            }
        }

        log.debug("Excel导入课程群组信息成功");
        return new JsonResult(true, "成功");
    }

    /**
     * 课程群组归档
     * @return JsonResult
     *
     * @author wyh
     * @since 2015-03-27
     */
    @RequestMapping(value = "/lessonHistory", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult importHistory() throws IOException {
        //批量归档课程群组信息
        courseGroupService.historyCourseGroups();

        log.debug("返回 课程群组归档成功");
        return new JsonResult(true, "成功");
    }

    /**
     * 导入课程安排
     * @param studentFile excel文件
     * @return JsonResult
     * @throws IOException
     *
     * @author wyh
     * @since 2015-03-30
     */
    @RequestMapping(value = "/lessonArrange", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult importCourseArrange(@RequestParam MultipartFile studentFile) throws IOException {
        List<CourseArrange> arrangeList = null;

        try {
            //校验上传的文件
            UploadUtil.validateFile(studentFile, fileTypes);

            //获取导入的课程安排集合
            arrangeList = courseArrangeService.readFromExcel(studentFile.getInputStream());

            //判断是否有存在数据
            courseArrangeService.checkForCode(arrangeList);

            //批量更新课程安排信息
            courseArrangeService.saveCourseArranges(arrangeList);

        } catch (UploadException | ExcelException ex) {
            log.debug("Excel导入课程安排信息失败");
            return new JsonResult(false, ex.getMessage().isEmpty() ? "Excel导入失败" : ex.getMessage());
        } finally {
            if (arrangeList != null) {
                log.debug("studentList != null");

                arrangeList.clear();
                arrangeList = null;
            }
        }

        log.debug("Excel导入课程安排信息成功");
        return new JsonResult(true, "成功");
    }

    /**
     * 导入班级信息
     * @param classFile excel文件
     * @return json
     * @throws IOException IO异常
     *
     * @author fanruiping
     * @since 2015-05-05
     */
    @RequestMapping(value = "/clazz", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult clazz(@RequestParam MultipartFile classFile) throws IOException {
        List<Clazz> classList = null;

        try {
            //校验上传的文件
            UploadUtil.validateFile(classFile, fileTypes);
            //获取导入的班级信息集合
            classList = classService.readFromExcel(classFile.getInputStream());

            //检查导入班级信息中的班级代码重复冲突问题
            classService.checkForNum(classList);

            //批量新增班级信息
            classService.saveClasses(classList);
        } catch (UploadException | ExcelException ex) {
            log.debug("import excel file failed");

            return new JsonResult(false, ex.getMessage().isEmpty() ? "Excel导入失败" : ex.getMessage());
        } finally {
            if (classList != null) {
                log.debug("classList != null");

                classList.clear();
                classList = null;
            }
        }

        log.debug("班级信息excel文件导入成功");
        return new JsonResult(true, "班级数据导入成功");
    }

    /**
     * 归档班级数据
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2015-05-05
     */
    @RequestMapping(value = "/classHistory", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult classHistory() throws IOException {
        //批量归档班级数据
        classService.setClassHistory();

        log.debug("班级数据归档成功");
        return new JsonResult(true, "成功");
    }
}
